package NewTmas.EditMode;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: abhatnag
 * Date: 8/12/11
 * Time: 5:20 PM
 * To change this template use File | Settings | File Templates.
 */
public class CallStoredProc extends EditStep
{
    Connection connection;

    private String storedProcString;
    private String[] storedProcArgsList;
    private final String displayString;

    @Override
    public String toString()
    {
        return displayString;
    }

    public CallStoredProc(String storedProcString, String[] storedProcArgsList, Connection connection)
    {
        this.storedProcString = storedProcString;
        this.storedProcArgsList = storedProcArgsList;
        this.connection = connection;
        this.displayString = displayFromProc(storedProcString, storedProcArgsList);
    }

    private static String displayFromProc(String storedProcString, String[] storedProcArgsList)
    {
        String displayString = storedProcString;
        for (String s : storedProcArgsList)
        {
            displayString = displayString.replaceFirst("\\?", s);
        }
        return displayString;
    }


    @Override
    public void exec() throws SQLException
    {
        CallableStatement proc = connection.prepareCall(storedProcString);
        for (int i = 0, storedProcArgsListLength = storedProcArgsList.length; i < storedProcArgsListLength; i++)
        {
            String s = storedProcArgsList[i];
            proc.setString(i + 1, s);
        }
        proc.execute();
    }

    /**
     * test main
     *
     * @param args ignored
     */
    public static void main(String[] args)
    {
        System.out.println(displayFromProc("{call tms.task_util.add_as(?,?,?)}", new String[]{"ASDF", "asdft", "asdf3"}));
    }
}
